import { Button, message } from "antd";
import { ModalForm, ProFormUploadButton } from "@ant-design/pro-form";
import { ImportOutlined } from "@ant-design/icons";
import HostModalForm from "./HostModalForm";
import { useIntl, FormattedMessage } from 'umi';

const BulkImport = (props) => {
  const {uploadFun, templateUrl, successCallback } = props;
  const intl = useIntl();

  const handlerBulkImport = async (fileObj) => {
    const hide = message.loading("正在创建");
    const token = localStorage.getItem("token");
    const formData = new FormData();
    formData.append("file", fileObj);

    await uploadFun(formData, token).then((res) => {
      hide()
      successCallback(res)
    }).catch((e) => {
      // message.error(e)
      console.log(e)
    })
  };

  return (
    <ModalForm
      title={intl.formatMessage({
        id: 'pages.hostTable.batchimport',
        defaultMessage: 'Batch import',
      })}
      width="440px"
      trigger={
        <Button type="primary">
          <ImportOutlined />
          <FormattedMessage id="pages.hostTable.batchimport" defaultMessage="cluster" />
        </Button>
      }
      // submitter={{
      //   searchConfig: {
      //     submitText: "确认",
      //     resetText: "取消",
      //   },
      // }}
      onFinish={async (values) => {
        const fileObj = values.file[0].originFileObj
        await handlerBulkImport(fileObj);
        return true;
      }}
    >
      <ProFormUploadButton
        accept=".xls, .xlsx"
        name="file"
        label={intl.formatMessage({
          id: 'pages.hostTable.importexcel',
          defaultMessage: 'Import excel file',
        })}
        max={2}
        extra={intl.formatMessage({
          id: 'pages.hostTable.importexcelfile',
          defaultMessage: 'Import excel file',
        })}
        addonAfter={<a href={templateUrl}><FormattedMessage id="pages.hostTable.temdownload" defaultMessage="Template download" /></a>}
        fieldProps={{
          beforeUpload: () => {return false}
        }}
      />
    </ModalForm>
  );
};

HostModalForm.defaultProps = {
  uploadFun: () => {},
  templateUrl: "/resource/主机导入模板.xls",
  successCallback: () => {}
}

export default BulkImport;
